//
//  CHFMDB.m
//  MySqliteDemo
//
//  Created by cyptt on 2022/8/18.
//

#import "CHFMDB.h"
#import "FMDB.h"

@interface CHFMDB()
@property(nonatomic,strong)FMDatabase * db;
@end
@implementation CHFMDB

static CHFMDB * _manage= nil;


+(instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_manage == nil) {
            _manage = [[self alloc]init];
        
        }
    });
    return _manage;
}

-(void)createDataBase:(NSString *)dbName{
    NSString * basepath = [[self path]stringByAppendingFormat:@"/%@",dbName];
    self.db = [FMDatabase databaseWithPath:basepath];

}

-(BOOL)open{
    BOOL isOpen = [self.db open];
    isOpen?NSLog(@"创建数据库成功"):NSLog(@"创建数据库失败");
    return  isOpen;
}
-(BOOL)close{
    BOOL isClose =  [self.db close];
    isClose?NSLog(@"关闭成功"):NSLog(@"关闭失败");
    return  isClose;
}

-(BOOL)createTable:(NSString *)tabName paramSql:(NSString *)paramSql{
    char *error = NULL;
    NSString * tabKey =[NSString stringWithFormat:@"create table if not exists %@ (id integer primary key autoincrement,",tabName] ;
    NSString * sqlString = [NSString stringWithFormat:@"%@%@)",tabKey,paramSql];

    int tableResult = [self.db executeUpdate:sqlString];

    if (tableResult == YES) {
        NSLog(@"创建表成功");
        return  YES;
    }else{
        NSLog(@"创建表失败:%s",error);
        return  NO;
    }
}

// 插入数据
- (void)insertTable:(NSString *)tabName paramDic:(NSDictionary *)paramDic
{
 
    NSMutableArray * keyArrs = [NSMutableArray array];
    NSMutableArray * valueArrs = [NSMutableArray array];
    for (NSString * key in [paramDic allKeys]) {
        [keyArrs addObject:key];
        NSString * valueString = [NSString stringWithFormat:@"'%@'",paramDic[key]];
        [valueArrs addObject:valueString];
    }
    
    NSString * keys = [keyArrs componentsJoinedByString:@","];
    NSString * values = [valueArrs componentsJoinedByString:@","];
   
    //  sql 语句
    NSString * sql = [NSString stringWithFormat:@"insert into %@ (%@) values (%@)",tabName,keys,values];

    NSLog(@"sql===%@",sql);
    
    // 执行 sql 语句
    if ([self.db open]) {
        BOOL success = [self.db executeUpdate:sql];
        
        success?NSLog(@"插入成功"):NSLog(@"插入失败");
    }else{
        NSLog(@"插入失败");
    }
}

/*
 查询所以数据
 */
-(nullable NSArray*)queryAll:(NSString *)tabName{
    
    NSString * selectSQL = [NSString stringWithFormat:@"select * from %@",tabName];
    NSLog(@"sql====%@",selectSQL);
   
    return [self queryConditionSql:selectSQL];
}

/*
 条件查询
 @param tabName 表名
 @param sql 全部sql语句
 */
-(nullable NSArray*)queryConditionSql:(NSString *)Sql{
    FMResultSet * set = [self.db executeQuery:Sql];
    
     int columnCount = [set columnCount];
     
    
     NSMutableArray * resultArr = [NSMutableArray array];
    if ([self.db open]) {
        while ([set next]) {
            
            NSMutableDictionary * dic =  [NSMutableDictionary dictionary];
            
            for (int i = 0;i<columnCount;i++){
                NSString * keyOC = [set columnNameForIndex:i];
                NSString *  valueOC = [set objectForColumnIndex:i];
                
                [dic setValue:valueOC forKey:keyOC];
            }
            
            [resultArr addObject:dic];
            
        }
    }
 
   

    return resultArr;
}


/*
 更新数据
 @param sql 全部sql语句
 */
-(BOOL)updateSql:(NSString *)sql{
    BOOL isSuccess = NO;
    if ([self.db open] == YES ) {
       isSuccess = [self.db executeUpdate:sql];
    }
    return YES;
}

/*
 删除数据
 @param sql 全部sql语句
 */
-(BOOL)deleteSql:(NSString *)sql{
    
    BOOL isSuccess = NO;
    if ([self.db open] == YES ) {
       isSuccess = [self.db executeUpdate:sql];
    }
    return isSuccess;
}
-(NSString * )path{
    NSString * cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject ;
    NSString * path = [cachePath stringByAppendingFormat:@"/chAppCache"];
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL isSucess = YES;
    BOOL isExist = [fileManager fileExistsAtPath:path];
    if (isExist ==NO) {
        NSError * error;
        if (![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
            isSucess =NO;
        }
    }
    
    return  path;
}

@end
